// 获取img的背景色
export const getBackgroundColorByImage = (image) => {
  var tempCanvas = document.createElement('canvas'),
      tempCtx = tempCanvas.getContext('2d');
  tempCanvas.width = image.naturalWidth;
  tempCanvas.height = image.naturalHeight;
  tempCtx.drawImage(image, 0, 0)

  const imageData = tempCtx.getImageData(0, 0, tempCanvas.width, tempCanvas.height);
  return parseImageData(imageData).maxAmountColor
}

// 获取canvas背景色
export const getBackgroundColorByCanvas = (ctx) => {
  const imageData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
  return parseImageData(imageData).maxAmountColor
}


// 解析像素组成
export const parseImageData = (imageData) => {
  const data = imageData.data || [],
        rgbaTotalMap = {},
        maxAmountColor = {
          color: '',
          count: 0
        },
        maxGorgeousColor = {
          color: '',
          gorgeous: 0,
        };

  for (let i = 0; i < data.length; i += 4) {
    const r = data[i],
          g = data[i + 1],
          b = data[i + 2],
          a = data[i + 3] / 255,
          colorArray = [r, g, b, a],
          colorKey = colorArray.join(', '),
          currentCount = rgbaTotalMap[colorKey] || 0;

    rgbaTotalMap[colorKey] = currentCount + 1;
  }

  for (const key of Object.keys(rgbaTotalMap)) {
    if(key == '0, 0, 0, 0') continue;   // 忽略透明色

    // 统计数量
    const colorCount = rgbaTotalMap[key];
    if (colorCount > maxAmountColor.count) {
      maxAmountColor.color = key;
      maxAmountColor.count = colorCount;
    }

    // 比较艳丽度
    const colorArray = key.split(', '),
          gorgeous = getColorDiffGorgeous(+colorArray[0], +colorArray[1], +colorArray[2]);
    if (gorgeous > maxGorgeousColor.gorgeous) {
      maxGorgeousColor.color = key;
      maxGorgeousColor.gorgeous = gorgeous;
    }
  }
  
  return {
    maxAmountColor: maxAmountColor.color,   // 数量最多的颜色
    maxGorgeousColor: maxGorgeousColor.color,   // 最艳丽的颜色
  };
};


// 获取rgb艳丽度
export const getColorDiffGorgeous = (r, g, b) => {
  var max = Math.max(r, g, b);
  var min = Math.min(r, g, b);
  return max - min
}

// 获取rgb亮度
export const calculateLuminance = (r, g, b) => {
  return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}

export const getPixelByCoord = (x, y, imageData) => {

}

export const getCoordByIndex = (index, imageData) => {

}

export const rgbaToObject = (rgbaString) => {
  const result = rgbaString.split(', ')
  if (result) {
    return {
      r: Number(result[0]),
      g: Number(result[1]),
      b: Number(result[2]),
      a: Number(result[3]),
    };
  } else {
    throw new Error('Invalid RGBA string format');
  }
}